package cmd

import (
	"docker-api/internal/domain"
	"docker-api/internal/model"
	"docker-api/pkg/util"
	"encoding/json"
	"errors"
	"fmt"
	"strings"
)

// ParseLSBRelease 解析 /etc/lsb-release 文件 获取系统信息
func ParseLSBRelease(content string) string {
	lines := strings.Split(content, "\n")
	for _, line := range lines {
		if strings.HasPrefix(line, "DISTRIB_DESCRIPTION=") {
			desc := strings.TrimPrefix(line, "DISTRIB_DESCRIPTION=")
			desc = strings.Trim(desc, `"`)
			return desc
		}
	}
	return "Linux"
}

// ParseOSRelease 解析 /etc/os-release 文件 获取系统信息
func ParseOSRelease(content string) string {
	lines := strings.Split(content, "\n")
	for _, line := range lines {
		if strings.HasPrefix(line, "PRETTY_NAME=") {
			name := strings.TrimPrefix(line, "PRETTY_NAME=")
			name = strings.Trim(name, `"`)
			return name
		}
	}
	return "Linux"
}

// ParseDarwinSystemInfo 解析 macOS 系统信息
func ParseDarwinSystemInfo(output string) (*SystemInfo, error) {
	lines := strings.Split(output, "\n")
	info := &SystemInfo{OS: "macOS"}

	for _, line := range lines {
		if strings.HasPrefix(line, "ProductName:") {
			info.OS = strings.TrimSpace(strings.TrimPrefix(line, "ProductName:"))
		} else if strings.HasPrefix(line, "ProductVersion:") {
			info.Version = strings.TrimSpace(strings.TrimPrefix(line, "ProductVersion:"))
		}
	}

	// 获取内核信息
	if kernel, err := GetKernelInfo(); err == nil {
		info.Kernel = kernel
	}

	return info, nil
}

// ParseSystemInfoOutput 解析 systeminfo 输出
func ParseSystemInfoOutput(output string) (*SystemInfo, error) {
	lines := strings.Split(output, "\n")
	info := &SystemInfo{OS: "Windows"}

	for _, line := range lines {
		line = strings.TrimSpace(line)

		// 尝试匹配英文版本
		if strings.HasPrefix(line, "OS Name:") {
			info.OS = strings.TrimSpace(strings.TrimPrefix(line, "OS Name:"))
		} else if strings.HasPrefix(line, "OS Version:") {
			info.Version = strings.TrimSpace(strings.TrimPrefix(line, "OS Version:"))
		}

		// 尝试匹配中文版本（处理可能的乱码）
		if strings.Contains(line, "OS") && strings.Contains(line, ":") &&
			(strings.Contains(line, "名称") || strings.Contains(line, "Name")) {
			parts := strings.SplitN(line, ":", 2)
			if len(parts) == 2 {
				candidate := strings.TrimSpace(parts[1])
				if candidate != "" && !strings.Contains(candidate, "?") {
					info.OS = candidate
				}
			}
		}

		if strings.Contains(line, "OS") && strings.Contains(line, ":") &&
			(strings.Contains(line, "版本") || strings.Contains(line, "Version")) {
			parts := strings.SplitN(line, ":", 2)
			if len(parts) == 2 {
				candidate := strings.TrimSpace(parts[1])
				if candidate != "" && !strings.Contains(candidate, "?") {
					info.Version = candidate
				}
			}
		}
	}

	if info.Version == "" {
		info.Version = "未知版本"
	}

	return info, nil
}

// ParsePowerShellOutput 解析 PowerShell JSON 输出
func ParsePowerShellOutput(output string) (*SystemInfo, error) {
	var result struct {
		Caption string `json:"Caption"`
		Version string `json:"Version"`
	}

	if err := json.Unmarshal([]byte(output), &result); err != nil {
		return nil, fmt.Errorf("解析 PowerShell 输出失败: %w", err)
	}

	osName := result.Caption
	if osName == "" {
		osName = "Windows"
	}

	osVersion := result.Version
	if osVersion == "" {
		osVersion = "未知版本"
	}

	return &SystemInfo{
		OS:      osName,
		Version: osVersion,
		Kernel:  osVersion,
	}, nil
}

// ExtractWMICValue 从 WMIC 输出中提取值
func ExtractWMICValue(output, key string) string {
	lines := strings.Split(output, "\n")
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if strings.HasPrefix(line, key+"=") {
			value := strings.TrimPrefix(line, key+"=")
			return strings.TrimSpace(value)
		}
	}
	return ""
}

// ParseDockerVersionText 解析文本格式的 Docker 版本信息
func ParseDockerVersionText(output string) (*DockerInfo, error) {
	lines := strings.Split(output, "\n")
	info := &DockerInfo{}
	inServerSection := false

	for _, line := range lines {
		line = strings.TrimSpace(line)

		// 检测是否进入 Server 部分
		if strings.HasPrefix(line, "Server:") || strings.HasPrefix(line, "Server version:") {
			inServerSection = true
			continue
		}

		// 如果遇到新的部分，退出 Server 部分
		if strings.HasPrefix(line, "Client:") && inServerSection {
			break
		}

		if inServerSection {
			// 解析版本信息
			if strings.HasPrefix(line, "Version:") {
				info.Version = strings.TrimSpace(strings.TrimPrefix(line, "Version:"))
			} else if strings.HasPrefix(line, "API version:") {
				info.APIVersion = strings.TrimSpace(strings.TrimPrefix(line, "API version:"))
			} else if strings.HasPrefix(line, "OS/Arch:") {
				osArch := strings.TrimSpace(strings.TrimPrefix(line, "OS/Arch:"))
				parts := strings.Split(osArch, "/")
				if len(parts) == 2 {
					info.OS = strings.TrimSpace(parts[0])
					info.Arch = strings.TrimSpace(parts[1])
				}
			}
		}
	}

	// 验证必要信息是否获取到
	if info.Version == "" {
		return nil, errors.New("无法解析 Docker 版本信息")
	}

	return info, nil
}

// ParseDockerVersionJSON 解析 Docker 版本 JSON 信息
func ParseDockerVersionJSON(output string) (*DockerInfo, error) {
	var versionResp DockerVersionResponse

	if err := json.Unmarshal([]byte(output), &versionResp); err != nil {
		return nil, fmt.Errorf("解析 Docker 版本 JSON 失败: %w", err)
	}

	// 验证必要信息是否获取到
	if versionResp.Server.Version == "" {
		return nil, errors.New("Docker Server 版本信息为空")
	}

	return &DockerInfo{
		Version:    versionResp.Server.Version,
		APIVersion: versionResp.Server.APIVersion,
		OS:         versionResp.Server.OS,
		Arch:       versionResp.Server.Arch,
	}, nil
}

// ParseDockerImageDetail 解析 Docker 镜像详细信息
func ParseDockerImageDetail(info domain.DockerImageInfo) ([]model.DockerImage, error) {
	var images []model.DockerImage

	for _, repoTag := range info.RepoTags {
		if repoTag == "<none>:<none>" {
			continue
		}

		parts := strings.Split(repoTag, ":")
		name := parts[0]
		tag := "latest"
		if len(parts) > 1 {
			tag = parts[1]
		}

		size := util.FormatSize(info.Size)

		image := model.DockerImage{
			ID:           strings.TrimPrefix(info.ID, "sha256:"),
			Name:         name,
			Tag:          tag,
			Size:         size,
			Created:      info.Created,
			Architecture: info.Architecture,
		}
		images = append(images, image)
	}

	return images, nil
}
